// pages/user/chat.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    array:[1],
    to_user_data:{},
    to_user_id:0,
    box_id:0,
    page:1,
    chatBntRecordText: '按住 说话',
    showChatBntBox: 0,
    toView: 'msgBoxBottom',
    voicePlaying: 0,
    pageY: 0,
    recordOver: 0,
    recording: 0,
    recordtime: 0,
    showRecordVaule: 0,
    msgList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({ to_user_id: options.to_user_id ? options.to_user_id:1});
    var user_info = wx.getStorageSync('user_info');
     this.setData({'user_info':user_info});   
    this.initData();
    this.revMessage();
  },
  initData:function(reload=0){
    if (reload==1){
      this.setData({
        page:1,
        loading:0,
        lastPage:0,
        msgList:[],
      });
    }
    this.loadToUserData();
    this.getMsg();
  },
  scrolltoupper:function(){
    this.getMsg(0);
  },
//聊天信息 
  getMsg:function(to_v=1){
    var that = this;
    var page = this.data.page;
    if (this.data.loading == 1 || this.data.lastPage==1){
      return false;
    }
    this.data.loading = 1;
    app.api("message/get", {
      page: page ,
      to_user_id:this.data.to_user_id,
      limit:30,
      order:'id desc',
    }, function (res) {
      that.data.loading = 0;
      if (res.code != 200) {
        app.alert(res.msg);
        return;
      }
      if (res.data.list.length==0){
        that.data.lastPage = 1;
      }
      page++;
      that.setData({ page: page, msgList: res.data.list.concat(that.data.msgList) });
      if (to_v == 1) {
        that.setToView();
      }
     
    })  
  },
//用户信息 
  loadToUserData:function(){
    var that = this;
    app.api("user/info", {
      user_id:this.data.to_user_id
    }, function (res) {
      if (res.code != 200) {
        app.alert(res.msg);
        return;
      }
     // console.log(res.data);
      wx.setNavigationBarTitle({
        title: res.data.nickname
      });
      
      that.setData({ to_user_info: res.data });
    })  
  },

  //打开地图
  showLocation:function(e){
    var longitude = e.currentTarget.dataset.longitude;
    var latitude = e.currentTarget.dataset.latitude;
    wx.openLocation({
      latitude: latitude,
      longitude: longitude,
      scale: 28
    });
  },
  //浏览图片
  previewImage: function (e) {
    var current = e.target.dataset.src;
    var urls=[];
    var msgList = this.data.msgList;
    for (var i in msgList){
      if (msgList[i]['msgType'] == "image" && msgList[i].data.imageUrl){
         urls.push(msgList[i].data.imageUrl);
      }
    }
    wx.previewImage({
      current: current,
      urls: urls
    })
  },
  //发送图片
  chooseImage: function (e) {
    var that = this;
    var sourceType = [];
    var source = e.currentTarget.dataset.source;
    sourceType.push(source);
    wx.chooseImage({
      count: 3,
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: sourceType, // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
        for (var i in tempFilePaths) {
          var filePath = tempFilePaths[i];
          app.upload(filePath, (res) => {
            var data = {
              msgType: 'image',
              data: {
                imageUrl: res.imageURL,
                showType: 'send',
              }
            };
            that.sendmessage(data);
          }) 
        }
      }
    })
  },
  revMessage: function () {
    var that = this;
    console.log("revMessage");
    app.revMessage("chatMessage", function (res) {
      console.log("chatMessage",res);
      var msgList = that.data.msgList;
      msgList.push(res)
      that.setData({ msgList: msgList });
      that.setToView();
    })
  },

  //滚动到最新消息位置
  setToView: function () {
   // var id = "msg" + (Number(this.data.msgList.length) - 1);
    
    var id ="msgBoxBottom";
    this.setData({ toView: id });
    // setTimeout(function(){
    //   wx.pageScrollTo({
    //     scrollTop: 8000
    //   })
    // },500);
    //  this.data.array.push(1);
    //  this.setData({ array: this.data.array});
    // wx.pageScrollTo({
    //     scrollTop: 890100
    //   })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    app.setPageData("user/chat",{'show':1});
    this.setToView();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    app.setPageData("user/chat", { 'show': 0 });
    console.log("onHide");
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    app.setPageData("user/chat", { 'show': 0 });
    console.log("onUnload");
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.initData(1);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  bodyclick: function () {
    this.setData({ showChatBntBox: 0 })
  },
  showBntAct: function (e) {
    var id = e.currentTarget.dataset.id;
    this.data.showChatBntBox != id ? this.setData({ showChatBntBox: id }) : this.setData({ showChatBntBox: 0 })
    console.log(id);
  },
  inputFocus: function () {
    //this.setData({ showChatBntBox: 0 });
  },
  //录音开始
  startRecord: function (e) {
    // console.log("startRecord",e);
    var that = this;
    var recordtime = 0;
    var timer = setInterval(function () {
      recordtime = recordtime+400;
      console.log(recordtime);
    }, 400);
    //console.log(that.data.recording, 'startRecord');
    this.setData({
      chatBntRecordText: '松开 结束',
      recording: 1,
      recordOver: 1,
      pageY: e.changedTouches[0].pageY
    });
    wx.showToast({
      title: '手指上滑，取消发送',
      image: '/image/record.png',
      duration: 200000
    })
    wx.startRecord({
      success: function (res) {
        var tempFilePath = res.tempFilePath;
        if (recordtime > 200 && that.data.recordOver == 1) {
          app.upload(tempFilePath, (res) => {
            var data = {
              msgType: 'voice',
              data:{
                voiceUrl: res.imageURL,
                duration: Math.ceil(recordtime / 1000),
              },
              showType: 'send',
            };
            that.sendmessage(data);
          }) 
        }
        console.log("success", recordtime, that.data.recordOver, tempFilePath);
      },
      complete: function () {
        if (that.data.recording === 0) {
          setTimeout(function () {
            //结束录音  
            wx.stopRecord()
          }, 100)
        }
        clearTimeout(timer);
      },
      fail: function (res) {
        console.log("fail", 'startRecord');
        //录音失败
      }
    })
    console.log('startRecord');
  },
  //录音结束
  stopRecord: function () {
    wx.hideToast();
    this.setData({ chatBntRecordText: '按住 说话', recording: 0 });
    wx.stopRecord();
    setTimeout(function () {
      //结束录音  
      wx.stopRecord()
    }, 200)
    console.log('stopRecord');
  },
  //取消说话
  cancelRecord: function () {
    wx.hideToast();
    this.setData({ chatBntRecordText: '按住 说话', recording: 0, recordOver: 0 });
  },
  //松开手指
  recordTouchmove: function (e) {
    var Y = this.data.pageY - e.changedTouches[0].pageY;
    if (Y > 20) {
      wx.showToast({
        title: '松开手指，取消发送',
        image: '/image/12.png',
        duration: 200000
      });
      this.setData({ chatBntRecordText: '松开 结束', recordOver: 0 });
    } else {
      wx.showToast({
        title: '手指上滑，取消发送',
        image: '/image/record.png',
        duration: 200000
      });
      this.setData({ chatBntRecordText: '松开 取消', recordOver: 1 });
    }
  },
  //播放语言
  playVoice: function (e) {
    var that = this;
    if (this.data.voicePlaying) {
      wx.stopVoice();
    } else {
      this.data.voicePlaying = 1;
      var voiceUrl = e.currentTarget.dataset.voiceurl;
      console.log(voiceUrl);
      wx.playVoice({
        filePath: voiceUrl,
        complete: function (e) {
          console.log(e);
        }
      });
      that.data.voicePlaying = 0;
    }
  },
  //发送地理位置
  chooseLocation: function () {
    var that = this;
    wx.chooseLocation({
      success: function (obj) {
        console.log("success", obj);
        var data = {
          msgType: 'location',
          data:{
          location: {
            name: obj.name,
            address: obj.address,
            latitude: obj.latitude,
            longitude: obj.longitude,
          },
          markers: [
            {
              iconPath: "/image/pin.png",
              id: 0,
              latitude: obj.latitude,
              longitude: obj.longitude,
              width: 25,
              height: 25
            }
          ]
          },
          showType: 'send',
        };
        that.sendmessage(data);
        // that.setData({ address: obj.address });
      },
      fail: function (obj) {
        console.log("fail", obj);
      },
      complete: function (obj) {
        console.log("complete", obj);
      }
    });
  },
  //confirmSend
  confirmSend:function(e){
    var data = {
      msgType: 'text',
      data: {
        text: e.detail.value,
      },
      showType: 'send',
    };
    this.sendmessage(data);
   // console.log(e.detail.value);
    this.setData({ msgValue:''});
  },
  //发送消息
  sendmessage: function (data) {
   // console.log(data);
    var msgList = this.data.msgList;
    msgList.push(data)
    this.setData({ msgList: msgList });
    this.setToView();
    
    //把消息保存在服务器 
    data.method ="POST";
    data.content = JSON.stringify(data.data);
    data.to_user_id = this.data.to_user_id;
    app.api("message/add",data,function(res){
      if(res.code!=200){
        app.alert(res.msg);
      }
       console.log(res);
    })
    //消息通websocket发送给对方 
    data.showType="rev";
    data.user = this.data.user_info;
    app.sendSocketMessage({
      userId: this.data.user_info.user_id,
      toUserId: this.data.to_user_id,
      content: data,
      dosometing: 'chatMessage',
    });
  },
})